import { useSelector } from "react-redux";
import { Route, Switch, useLocation, Redirect } from "react-router-dom";

import Home from "../pages/Home";
import Login from "../pages/Login";
import Logon from "../pages/Logon";
import User from "../pages/User";
const RouterPages = () => {
  const loginInfo = useSelector(state => state.user.loginInfo);
  const local = useLocation();
  const needLogin = [ "/home/edit", "/user" ];
  const routeRootHandles = {
    "/login"() {
      return loginInfo ? <Redirect to="/"></Redirect> : "";
    },
    "/logon"() {
      return this["/login"]();
    },
    "*"() {
      return !loginInfo && needLogin.indexOf(local.pathname) > -1 ? <Redirect to="/login"></Redirect> : "";
    }
  }
  return (
    <Switch>
      {routeRootHandles.hasOwnProperty(local.pathname) ? routeRootHandles[local.pathname]() : routeRootHandles["*"]()}
      <Route exact path="/">
        <Redirect to="/home"></Redirect>
      </Route>
      <Route path="/home" component={Home}></Route>
      <Route path="/login" component={Login}></Route>
      <Route path="/logon" component={Logon}></Route>
      <Route path="/user" component={User}></Route>
    </Switch>
  )
};

export default RouterPages;